import React, {
  memo,
  useState,
  useEffect,
  forwardRef,
  useImperativeHandle,
  useCallback,
} from "react";
import { Button, Table, Row, Col, Pagination } from "antd";
import PropTypes from "prop-types";

import { custom } from "services/common";

interface Props {
  tableConfig: {
    thead: any[];
    requestData: {
      url: string;
      method: string;
      data?: { pageNumber?: number; pageSize?: number; name?: string };
    };
    rowKey: string;
    border?: boolean;
    isShowBatch?: boolean;
    isShowCheckbox?: boolean;
  };
  batch: any;
  [propName: string]: any;
}

const HYTableUI = forwardRef((props: Props, ref: any) => {
  const { tableConfig, batch } = props;

  const {
    border = true,
    rowKey,
    isShowBatch = false,
    isShowCheckbox = true,
  } = tableConfig;
  //hooks-data
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  //   const [pageNumber, setPageNumber] = useState(1); 如果要针对分页做缓存 就需要把这个页面保存下来
  const [pageSize, setPageSize] = useState<number | undefined>(10);
  const [currentItemAry, setCurrentItemAry] = useState<any[]>([]); //批量删除选中的item
  const [id, setId] = useState<string>();

  // 其它逻辑
  const getInitData = useCallback(
    async (data: {}) => {
      const { requestData } = tableConfig;
      if (data) {
        //设置默认值的一种方式
        requestData.data = { ...requestData.data, ...data };
      }
      const res: any = await custom(requestData);
      if (res.data.data.length > 0) {
        setDataSource(res.data.data);
        setTotal(res.data.total);
      }
      if (res.data.data.length === 0) {
        setDataSource([]);
        setTotal(0);
      }
    },
    [tableConfig]
  );
  const init = useCallback(
    (data = {}) => {
      getInitData(data);
    },
    [getInitData]
  );
  // 生命周期
  useEffect(() => {
    init();
  }, [init]);

  //  其它逻辑
  const changePageCurrent = (
    pageNumber: number,
    pageSizes?: number | undefined
  ) => {
    //选择的页码
    if (pageNumber !== 0) {
      //   setPageNumber(pageNumber);
      setPageSize(pageSize);
      getInitData({ pageNumber, pageSize: pageSizes });
    }
    if (pageSize !== pageSizes) {
      //   setPageNumber(1);
      setPageSize(pageSizes);
      getInitData({ pageNumber: 1, pageSize: pageSizes });
    }
  };
  const changePageSize = (num: number) => {
    console.log(num);
    if (num !== 0) {
      //   setPageNumber(num);
      getInitData({ pageNumber: num, pageSize });
    }
  };
  const selectedRowKeys = {
    // record点击的单个item selected是否选中 selectedRow选中的数组
    onSelect: (record: any, selected: boolean, selectedRows: any) => {
      const idString = selectedRows.map((item: any) =>(item[rowKey])).join(",") || "";
      setId(idString);
      setCurrentItemAry(selectedRows);
    },
    onSelectAll: (selected: boolean, selectedRows: any) => {
      const idString = selectedRows.map((item: any) =>(item[rowKey])).join(",") || "";
      setId(idString);
      setCurrentItemAry(selectedRows);
    },
  };

  // ref ---将自己封装的组件里面的方法抛出去
  useImperativeHandle(ref, () => ({
    init: getInitData,
  }));

  return (
    <>
      <Table
        columns={tableConfig.thead}
        dataSource={dataSource}
        bordered={border}
        rowKey={rowKey}
        rowSelection={isShowCheckbox ? selectedRowKeys : undefined}
        pagination={false}
      ></Table>
      {/* 分页+批量删除 */}
      <Row style={{ marginTop: "20px" }}>
        <Col span={8}>
          {isShowBatch ? (
            <Button onClick={() => batch(id, currentItemAry)}>批量删除</Button>
          ) : (
            <span />
          )}
        </Col>
        <Col span={16}>
          {/* 分页还可以增加配置项  */}
          <Pagination
            onChange={changePageCurrent}
            onShowSizeChange={changePageSize}
            className="pull-right"
            total={total}
            defaultCurrent={1}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `Total ${total} items`}
          />
        </Col>
      </Row>
    </>
  );
});
// 校验参数
HYTableUI.propTypes = {
  tableConfig: PropTypes.object, //配置项
  batch: PropTypes.func, //批量删除-返回一个id字符串出去
};
// 参数默认
HYTableUI.defaultProps = {};

export default memo(HYTableUI);
